package com.shop.admin.service.impl;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shop.entity.dto.AdminWares.*;
import com.shop.entity.pojo.*;
import com.shop.admin.mapper.*;
import com.shop.admin.service.WaresService;
import com.shop.utils.common.enums.Code;
import com.shop.utils.common.enums.Message;
import com.shop.utils.common.result.PageResponseResult;
import com.shop.utils.common.result.Result;
import com.shop.utils.config.BaseContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;


@Service
@Slf4j
public class WaresServiceImpl extends ServiceImpl<WaresMapper, Wares> implements WaresService{


    @Autowired
    private WaresMapper waresMapper;
    @Autowired
    private AdminUserMapper adminUserMapper;
    @Autowired
    private StyleMapper styleMapper;
    @Autowired
    private CostMapper costMapper;

    @Autowired
    private ImagesMapper waresImagesMapper;
    @Autowired
    private BrandsMapper brandsMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public Result saveWares(AdminWaresSaveDto dto) {
        long start = System.currentTimeMillis();
        log.info("后台管理-添加商品");
        Wares wares=new Wares();
        Style style=new Style();
        Cost cost=new Cost();
        if (dto==null||dto.getWaresName()==null||dto.getWaresPrice()==Message.Check_Int_Null||dto.getBrandsId()==null) {
            log.info("dto为空");
            return Result.errorResult(Code.PARAM_REQUIRE);
        }
        if (dto.getCostMessage()==null||dto.getHaveStyle()==null) {
            log.info("dto数据有必写数据为空");
            return Result.errorResult(Code.PARAM_REQUIRE);
        }
        Images waresImages = waresImagesMapper.selectById(dto.getWaresImagesId());
        if (waresImages==null) {
            log.info("未查询到该图片素材");
            return Result.errorResult(Code.PARAM_INVALID);
        }
        Long adminId = BaseContext.getCurrentId();
        Brands brands = brandsMapper.selectById(dto.getBrandsId());
        if (brands==null) {
            return Result.errorResult(Code.DATA_NOT_EXIST);
        }
        AdminUser adminUsers = adminUserMapper.selectOne(Wrappers.<AdminUser>lambdaQuery().eq(AdminUser::getId, adminId));
        if (adminUsers==null||adminId==null) {
            log.info("未查询到该管理员");
            return Result.errorResult(Code.DATA_NOT_EXIST);
        }

        /**
         * 添加商品
         */

        List<Wares> waresList = waresMapper.selectList(Wrappers.<Wares>lambdaQuery().eq(Wares::getWaresName, dto.getWaresName()));
        if (!CollectionUtils.isEmpty(waresList)||waresList.size()>Message.Check_Int_Null) {
            log.info("wares已存在wares:{}",waresList);
            return Result.errorResult(Code.DATA_EXIST);
        }
        wares=wares.builder()
                .waresName(dto.getWaresName())
                .waresImages(waresImages.getUrl())
                .brandsId(dto.getBrandsId())
                .saveAdmin(adminUsers.getName())
                .saveTime(String.valueOf(LocalDateTime.now())).build();
        int saveWares = waresMapper.saveWares(wares);
        if (saveWares==Message.Check_Int_False) {
            log.info("wares添加失败");
            return Result.errorResult(Code.SERVER_ERROR);
        }
        log.info("wares：{}",wares);
        Long waresId=wares.getId();
        log.info("wares.getId:{}",waresId);

        /**
         * 添加款式
         */
        log.info("添加商品款式款式");
        if (dto.getHaveStyle().equals("save")) {
            if (dto.getStyleName()==null||dto.getStyleImagesId()==null) {
                log.info("商品款式添加数据为空");
                log.info("开始清空添加的商品数据");
                waresMapper.deleteById(wares.getId());
                return Result.errorResult(Code.PARAM_REQUIRE);
            }
            Images styleImages=waresImagesMapper.selectById(dto.getStyleImagesId());
            if (styleImages==null) {
                log.info("未查询到该图片素材");
                log.info("开始清空添加的商品数据");
                waresMapper.deleteById(wares.getId());
                return Result.errorResult(Code.SERVER_ERROR);
            }
            style=style.builder()
                    .waresId(waresId)
                    .styleName(dto.getStyleName())
                    .styleImages(styleImages.getUrl())
                    .saveAdmin(adminUsers.getName())
                    .saveTime(String.valueOf(LocalDateTime.now())).build();
            log.info("style:{}",style);
            List<Style> styleList = styleMapper.getList(style);
            if (!CollectionUtils.isEmpty(styleList)||styleList.size()>Message.Check_Int_Null) {
                log.info("style已存在style:{}",styleList);
                log.info("开始清空添加的商品数据");
                waresMapper.deleteById(wares.getId());
                return Result.errorResult(Code.DATA_EXIST);
            }


        }else if (dto.getHaveStyle().equals("noSave")){
            log.info("商品无款式");
            style=style.builder()
                    .styleName(dto.getWaresName())
                    .styleImages(waresImages.getUrl())
                    .waresId(waresId)
                    .saveAdmin(adminUsers.getName())
                    .saveTime(String.valueOf(LocalDateTime.now())).build();
        }else {
            log.info("商品款式选择数据传输错误");
            waresMapper.deleteById(wares.getId());
            return Result.errorResult(Code.PARAM_INVALID);
        }
        int saveStyle = styleMapper.insert(style);
        if (saveStyle==Message.Check_Int_False) {
            log.info("款式添加失败");
            log.info("开始清空添加的商品数据");
            waresMapper.delById(wares.getId());
            return Result.errorResult(Code.SERVER_ERROR);
        }

        /**
         * 添加价格
         */
        log.info("添加价格");
        List<Cost> costList = costMapper.selectList(Wrappers.<Cost>lambdaQuery()
                .eq(Cost::getWaresId, wares.getId())
                .eq(Cost::getStyleId, style.getId())
                .eq(Cost::getCostMessage, dto.getCostMessage()));
        if (!CollectionUtils.isEmpty(costList)||costList.size()>Message.Check_Int_Null) {
            log.info("商品价格已存在");
            log.info("开始清空添加的商品数据与商品款式数据");
            waresMapper.deleteById(wares.getId());
            styleMapper.deleteById(style.getId());
            return Result.errorResult(Code.DATA_EXIST);
        }
        cost=cost.builder()
                .waresId(wares.getId())
                .styleId(style.getId())
                .costMessage(dto.getCostMessage())
                .waresPrice(dto.getWaresPrice())
                .saveAdmin(adminUsers.getName())
                .saveTime(String.valueOf(LocalDateTime.now())).build();
        int saveCost = costMapper.insert(cost);
        if (saveCost==Message.Check_Int_False) {
            log.info("价格添加失败");
            log.info("开始清空添加的商品数据与商品款式数据");
            waresMapper.delById(wares.getId());
            styleMapper.delById(style.getId());
            return Result.errorResult(Code.SERVER_ERROR);
        }
        long end = System.currentTimeMillis();
        log.info("后台管理添加商品进程完成，总耗时:{}",(end-start));

        return Result.okResult(Code.SUCCESS);
    }

    @Override
    public Result removeWares(AdminWaresRemoveDto dto) {
        long start = System.currentTimeMillis();
        log.info("删除商品");
        if (dto==null||dto.getWaresId()==null||dto.getRemoveMemo()==null) {
            log.info("未接收到前端传来的数据");
            return Result.errorResult(Code.PARAM_REQUIRE);
        }
        Long adminId = BaseContext.getCurrentId();
        AdminUser adminUser = adminUserMapper.selectById(adminId);
        if (adminId==null||adminUser==null) {
            log.info("未查询到该管理员");
            return Result.errorResult(Code.DATA_NOT_EXIST);
        }
        Wares wares = waresMapper.selectById(dto.getWaresId());
        if (wares==null) {
            log.info("未查询到需要删除的商品");
            return Result.errorResult(Code.DATA_NOT_EXIST);
        }
        List<Style> styleList = styleMapper.selectList(Wrappers.<Style>lambdaQuery().eq(Style::getWaresId, dto.getWaresId()));
        List<Cost> costList = costMapper.selectList(Wrappers.<Cost>lambdaQuery().eq(Cost::getWaresId, dto.getWaresId()));
        if (!CollectionUtils.isEmpty(styleList)||styleList.size()>Message.Check_Int_Null||!CollectionUtils.isEmpty(costList)||costList.size()>Message.Check_Int_Null) {
            if (dto.getRemoveRelated().equals("true")) {
                log.info("开始删除关联的款式与价格");

                Style style=new Style().builder().removeAdmin(adminUser.getName()).removeMemo(dto.getRemoveMemo()).build();
                int updateStyle = styleMapper.update(style, Wrappers.<Style>lambdaQuery().eq(Style::getWaresId, dto.getWaresId()));
                int deleteStyle = styleMapper.delete(Wrappers.<Style>lambdaQuery().eq(Style::getWaresId, dto.getWaresId()));

                Cost cost=new Cost().builder().removeAdmin(adminUser.getName()).removeMemo(dto.getRemoveMemo()).build();
                int updateCost = costMapper.update(cost, Wrappers.<Cost>lambdaQuery().eq(Cost::getWaresId, dto.getWaresId()));
                int deleteCost = costMapper.delete(Wrappers.<Cost>lambdaQuery().eq(Cost::getWaresId, dto.getWaresId()));
                if (updateStyle==Message.Check_Int_False||deleteStyle==Message.Check_Int_False||updateCost==Message.Check_Int_False||deleteCost==Message.Check_Int_False) {
                    log.info("关联删除失败");
                    return Result.errorResult(Code.SERVER_ERROR);
                }
            }else if (dto.getRemoveRelated().equals("false")){
                log.info("取消删除关联商品,终止方法");
                return Result.errorResult(Code.DATA_EXIST);
            }
            else {
                return Result.errorResult(Code.PARAM_INVALID);
            }
        }

        Wares newWares=new Wares();
        newWares= newWares.builder()
                .removeMemo(dto.getRemoveMemo())
                .removeAdmin(adminUser.getName()).build();
        boolean update = update(newWares, Wrappers.<Wares>lambdaUpdate().eq(Wares::getId, dto.getWaresId()));
        if (!update) {
            log.info("修改失败");
            return Result.errorResult(Code.SERVER_ERROR);
        }
        int delWares = waresMapper.deleteById(dto.getWaresId());
        if (delWares==Message.Check_Int_False) {
            log.info("删除失败");
            return Result.errorResult(Code.SERVER_ERROR);
        }
        long end = System.currentTimeMillis();
        log.info("后台管理删除商品进程完成，总耗时:{}",(end-start));
        return Result.okResult(Code.SUCCESS);
    }

    @Override
    public Result openWares(AdminWaresOpenDto dto) {
        long start = System.currentTimeMillis();
        log.info("后台管理-恢复商品");
        if (dto.getWaresId()==null) {
            return Result.errorResult(Code.PARAM_REQUIRE);
        }
        Long adminId = BaseContext.getCurrentId();
        AdminUser adminUser = adminUserMapper.selectById(adminId);
        Wares byId = waresMapper.getOne(dto.getWaresId());
        if (adminId==null||byId==null||adminUser==null) {
            return Result.errorResult(Code.DATA_NOT_EXIST);
        }
        if (byId.getIsDelete()==Message.Delete_False) {
            return Result.errorResult(Code.PARAM_INVALID);
        }
        Wares wares=new Wares();
        wares= wares.builder()
                .id(dto.getWaresId())
                .isDelete(Message.Delete_True)
                .removeAdmin(null)
                .removeMemo(null)
                .saveAdmin(adminUser.getName())
                .saveTime(String.valueOf(LocalDateTime.now())).build();
        boolean update = waresMapper.updateDelete(wares);
        if (!update) {
            return Result.errorResult(Code.SERVER_ERROR);
        }
        long end = System.currentTimeMillis();
        log.info("后台管理恢复商品进程完成，总耗时:{}",(end-start));
        return Result.okResult(Code.SUCCESS);
    }

    @Override
    public Result updateWares(AdminWaresUpdateDto dto) {
        long start = System.currentTimeMillis();
        log.info("后台管理-修改商品");
        if (dto.getWaresId()==null) {
            log.info("未接收到前端传来的数据");
            return Result.errorResult(Code.PARAM_REQUIRE);
        }
        Long adminId = BaseContext.getCurrentId();
        AdminUser adminUsers = adminUserMapper.selectOne(Wrappers.<AdminUser>lambdaQuery().eq(AdminUser::getId, adminId));
        if (adminUsers==null||adminId==null) {
            log.info("未查询到该管理员");
            return Result.errorResult(Code.PARAM_INVALID);
        }
        Wares oldWares = waresMapper.selectById(dto.getWaresId());
        if (oldWares==null) {
            log.info("未查询到需要修改的商品");
            return Result.errorResult(Code.DATA_NOT_EXIST);
        }
        String waresImgUrl= oldWares.getWaresImages();
        if (dto.getWaresImagesId()!=null) {
            log.info("修改新的图片");
            Images waresImages = waresImagesMapper.selectById(dto.getWaresImagesId());
            if (waresImages==null) {
                log.info("未查询到该图片素材");
                return Result.errorResult(Code.DATA_NOT_EXIST);
            }
            waresImgUrl = waresImages.getUrl();
        }
        String waresName=oldWares.getWaresName();
        if (dto.getWaresName()!=null) {
            log.info("修改新的名称");
            List<Wares> waresList = waresMapper.selectList(Wrappers.<Wares>lambdaQuery().eq(Wares::getWaresName, dto.getWaresName()));
            if (!CollectionUtils.isEmpty(waresList)||waresList.size()>Message.Check_Int_Null) {
                log.info("该商品名已存在");
                return Result.errorResult(Code.DATA_EXIST);
            }
            waresName= dto.getWaresName();
        }
        Wares wares=new Wares();
        wares=wares.builder()
                .waresName(waresName)
                .waresImages(waresImgUrl)
                .saveAdmin(adminUsers.getName()).build();

        boolean update = update(wares, Wrappers.<Wares>lambdaUpdate().eq(Wares::getId, dto.getWaresId()));
        if (!update) {
            log.info("修改失败");
            return Result.errorResult(Code.SERVER_ERROR);
        }
        long end = System.currentTimeMillis();
        log.info("后台管理修改商品进程完成，总耗时:{}",(end-start));

        return Result.okResult(Code.SUCCESS);
    }

    @Override
    public Result<Wares> updateGetWares(AdminWaresUpdateForGetDto dto) {
        long start = System.currentTimeMillis();
        log.info("后台管理-修改商品数据回显");
        if (dto.getWaresId()==null) {
            log.info("未接收到前端传来的商品ID");
            return Result.errorResult(Code.PARAM_REQUIRE);
        }
        Wares wares = getOne(Wrappers.<Wares>lambdaQuery().eq(Wares::getId, dto.getWaresId()));
        if (wares==null) {
            log.info("未查询到该商品数据");
            return Result.errorResult(Code.DATA_NOT_EXIST);
        }
        long end = System.currentTimeMillis();
        log.info("后台管理修改商品回显进程完成，总耗时:{}",(end-start));
        return Result.okResult(wares);
    }

    @Override
    public Result pullWares(AdminWaresPullDto dto) {
        long start = System.currentTimeMillis();
        log.info("后台管理-下架商品");
        if (dto.getWaresId()==null||dto.getMemo()==null) {
            return Result.errorResult(Code.PARAM_REQUIRE);
        }
        Long userId = BaseContext.getCurrentId();
        if (userId==null) {
            return Result.errorResult(Code.NEED_LOGIN);
        }
        AdminUser adminUser = adminUserMapper.selectById(userId);
        if (adminUser==null) {
            return Result.errorResult(Code.NEED_LOGIN);
        }
        Wares checkWares = waresMapper.selectById(dto.getWaresId());
        if (checkWares==null) {
            return Result.errorResult(Code.DATA_NOT_EXIST);
        }
        Wares wares=new Wares();
        Style style=new Style();
        Cost cost=new Cost();
        wares= wares.builder()
                .state(Message.Pull)
                .removeAdmin(adminUser.getName())
                .removeMemo(dto.getMemo()).build();
        style= style.builder()
                .state(Message.Pull)
                .removeAdmin(adminUser.getName())
                .removeMemo(dto.getMemo()).build();
        cost= cost.builder()
                .state(Message.Pull)
                .removeAdmin(adminUser.getName())
                .removeMemo(dto.getMemo()).build();
        int waresPull = waresMapper.update(wares, Wrappers.<Wares>lambdaUpdate().eq(Wares::getId, dto.getWaresId()));
        int stylePull = styleMapper.update(style, Wrappers.<Style>lambdaUpdate().eq(Style::getWaresId, dto.getWaresId()));
        int costPull = costMapper.update(cost, Wrappers.<Cost>lambdaUpdate().eq(Cost::getWaresId, dto.getWaresId()));
        if (waresPull==Message.Check_Int_False||stylePull==Message.Check_Int_False||costPull==Message.Check_Int_False) {
            return Result.errorResult(Code.SERVER_ERROR);
        }
        long end = System.currentTimeMillis();
        log.info("后台管理下架商品进程完成，总耗时:{}",(end-start));
        return Result.okResult(Code.SUCCESS);
    }

    @Override
    public Result putWares(AdminWaresPutDto dto) {
        long start = System.currentTimeMillis();
        if (dto.getWaresId()==null) {
            return Result.errorResult(Code.PARAM_REQUIRE);
        }
        Long userId = BaseContext.getCurrentId();
        if (userId==null) {
            return Result.errorResult(Code.NEED_LOGIN);
        }
        AdminUser adminUser = adminUserMapper.selectById(userId);
        if (adminUser==null) {
            return Result.errorResult(Code.NEED_LOGIN);
        }
        Wares checkWares = waresMapper.selectById(dto.getWaresId());
        if (checkWares==null) {
            return Result.errorResult(Code.DATA_NOT_EXIST);
        }
        Wares wares=new Wares();
        Style style=new Style();
        Cost cost=new Cost();
        wares= wares.builder()
                .state(Message.Put)
                .saveAdmin(adminUser.getName())
                .saveTime(String.valueOf(LocalDateTime.now())).build();
        style= style.builder()
                .state(Message.Put)
                .saveAdmin(adminUser.getName())
                .saveTime(String.valueOf(LocalDateTime.now())).build();
        cost= cost.builder()
                .state(Message.Put)
                .saveAdmin(adminUser.getName())
                .saveTime(String.valueOf(LocalDateTime.now())).build();
        int waresPull = waresMapper.update(wares, Wrappers.<Wares>lambdaUpdate().eq(Wares::getId, dto.getWaresId()));
        int stylePull = styleMapper.update(style, Wrappers.<Style>lambdaUpdate().eq(Style::getWaresId, dto.getWaresId()));
        int costPull = costMapper.update(cost, Wrappers.<Cost>lambdaUpdate().eq(Cost::getWaresId, dto.getWaresId()));
        if (waresPull==Message.Check_Int_False||stylePull==Message.Check_Int_False||costPull==Message.Check_Int_False) {
            return Result.errorResult(Code.SERVER_ERROR);
        }
        long end = System.currentTimeMillis();
        log.info("后台管理上架商品进程完成，总耗时:{}",(end-start));
        return Result.okResult(Code.SUCCESS);
    }

    @Override
    public Result getWaresList(AdminWaresListDto dto) {
        long start = System.currentTimeMillis();
        log.info("后台管理-获取商品列表");
        dto.checkParam();
        Page<Wares> page=new Page<>(dto.getPage(),dto.getSize());
        String key=Message.Admin_key_Wares_All;
        Page<Wares> check = (Page<Wares>) redisTemplate.opsForValue().get(key);
        if (check!=null&&!check.equals("")) {
            log.info("浏览缓存");
            Result result=new PageResponseResult(dto.getPage(),dto.getSize(), (int) check.getTotal());
            result.setData(check.getRecords());
            long end = System.currentTimeMillis();
            log.info("后台管理查看商品列表进程完成，总耗时:{}",(end-start));
            return Result.okResult(check);
        }
        log.info("浏览数据库");
        Page<Wares> value = waresMapper.getAllByPage(page, dto);
        Result result=new PageResponseResult(dto.getPage(),dto.getSize(), (int) value.getTotal());
        result.setData(value.getRecords());
        redisTemplate.opsForValue().set(key,value);
        long end = System.currentTimeMillis();
        log.info("后台管理查看商品列表进程完成，总耗时:{}",(end-start));
        return Result.okResult(result);
    }

}
